package com.hoko.blur.opengl.framebuffer;

import ohos.agp.render.opengl.GLES20;

import com.hoko.blur.api.IFrameBuffer;
import com.hoko.blur.api.ITexture;

/**
 * 帧缓冲
 *
 * @since 2021/08/03
 */
class FrameBuffer implements IFrameBuffer {

    /**
     * m帧缓冲id
     */
    private int mFrameBufferId;

    /**
     * 米结构
     */
    private ITexture mTexture;

    /**
     * 帧缓冲
     */
    FrameBuffer() {
        create();
    }

    /**
     * 帧缓冲
     *
     * @param id id
     */
    FrameBuffer(int id) {
        mFrameBufferId = id;
    }

    /**
     * id
     *
     * @return int
     */
    public int id() {
        return mFrameBufferId;
    }

    /**
     * id
     *
     * @param frameBufferId 帧缓冲id
     */
    public void id(int frameBufferId) {
        mFrameBufferId = frameBufferId;
    }

    /**
     * 创建
     */
    @Override
    public void create() {
        final int[] frameBufferIds = new int[1];

//        GLES20.glGenFramebuffers(1, frameBufferIds, 0);
        GLES20.glGenFramebuffers(1, frameBufferIds);

        mFrameBufferId = frameBufferIds[0];
    }

    /**
     * 绑定纹理
     *
     * @param texture 纹理
     */
    @Override
    public void bindTexture(ITexture texture) {
        if (texture == null) {
            return;
        }
        mTexture = texture;

        if (texture.id() != 0) {
            GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBufferId);

            GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
                    GLES20.GL_TEXTURE_2D, texture.id(), 0);
        }

        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    }

    /**
     * 绑定纹理
     *
     * @return {@link ITexture}
     */
    public ITexture bindTexture() {
        return mTexture;
    }

    /**
     * 结合自
     */
    @Override
    public void bindSelf() {
        if (mFrameBufferId != 0) {
            GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBufferId);
        }
    }

    /**
     * 删除
     */
    @Override
    public void delete() {
        if (mFrameBufferId != 0) {
//            GLES20.glDeleteFramebuffers(1, new int[]{mFrameBufferId}, 0);
            GLES20.glDeleteFramebuffers(1, new int[]{mFrameBufferId});
        }
    }
}
